package com.session04.am.frames;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChatFrame extends JFrame {

    private JList list;
    private JTextArea area;
    private JTextField txtInput;
    private JButton btnSend;
    private JPanel p1, p2;

    public ChatFrame() {
        this.setTitle("聊天窗口");
        this.setBounds(400, 100, 400, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

        list = new JList();
        list.setFixedCellWidth(100);
        list.setFixedCellHeight(30);
        DefaultListModel listModel = new DefaultListModel();
        listModel.addElement("Spring");
        listModel.addElement("SpringBoot");
        listModel.addElement("SpringMVC");
        list.setModel(listModel);

        //右边的大容器
        p1 = new JPanel();
        //设置边框布局
        p1.setLayout(new BorderLayout());
        //大输入框放入到正中
        area = new JTextArea();
        p1.add(area, BorderLayout.CENTER);

        //小的布局容器
        p2 = new JPanel();
        //JPanel默认是流式布局，所以必须给输入框长度
        txtInput = new JTextField(20);
        btnSend = new JButton("发送");
        p2.add(txtInput);
        p2.add(btnSend);

        btnSend.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String txt = txtInput.getText();
                area.setText(area.getText() + txt + "\n");
                txtInput.setText("");
            }
        });

        p1.add(p2, BorderLayout.SOUTH);

        this.add(list, BorderLayout.WEST);
        this.add(p1);
    }
}
